#!/bin/bash

# JayVii
# https://notabug.org/jayvii
# update-NodeJS-miniscript v0.1

NODE_VER=$1
BUILD_DIR="~/TMP_NODE_BUILDDIR"

if [ -z "$1" ]; then
	echo "########## HELP"
	echo "# ./update.nodejs-miniscript.run [VERSION]"
	echo "# ex: ./update.nodejs-miniscript.run 5.5.0"
	echo "# any version from https://github.com/nodejs/node/archive/"
	echo "# or 'git'"
	echo "#"
	echo "########## Dependencies"
	echo "# https://github.com/nodejs/node#build"
	exit 1
fi

mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}"

if [ "$NODE_VER" = git ]; then
	git clone https://github.com/nodejs/node node-${NODE_VER}
else
	wget https://github.com/nodejs/node/archive/v${NODE_VER}.tar.gz
	tar -zxvf v${NODE_VER}.tar.gz
	rm v${NODE_VER}.tar.gz
fi

cd "${BUILD_DIR}/node-${NODE_VER}"
./configure
make
su -c "make install" root

rm -rf "${BUILD_DIR}"

echo "linking '/usr/local/bin/node' to '/usr/bin/nodejs'?"
if [ -f /usr/bin/nodejs ]; then
	su -c "mv /usr/bin/nodejs /usr/bin/nodejs.real
		ln -s /usr/local/bin/node /usr/bin/nodejs" root
else
	su -c "ln -s /usr/local/bin/node /usr/bin/nodejs" root
fi
